<?php
/**
 * Created by PhpStorm.
 * @author LiShaoWei
 * @param Date : 2016/4/7
 * @param Time : 16:31
 * @since 1.0
 */
namespace app\controllers;
use yii\web\Controller;


class TestUserController extends Controller{
    protected $_server;
    public $enableCsrfValidation = false;

    public function beforeAction($action)
    {

        if (!parent::beforeAction($action)) return false;

        $dsn      = 'mysql:dbname=test1;host=localhost';
        $username = 'root';
        $password = '123456';
        //ini_set('display_errors',1);

        //error_reporting(E_ALL);

        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
        $server = new \OAuth2\Server($storage, array('enforce_state'=>false));
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
        $this->_server = $server;
        return true;
    }


    public function actionToken()
    {
        $this->_server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }


    public function actionResource()
    {
        if (!$this->_server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            return $this->_server->getResponse()->send();
        }
        echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
    }

    public function actionAuthorize()
    {
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();
        if (!$this->_server->validateAuthorizeRequest($request, $response)) {
            return $response->send();
        }
        if (empty($_POST)) {
            return ' <form method="post">
					<label>Do You Authorize TestClient?</label><br />
					<input type="submit" name="authorized" value="yes">
					<input type="submit" name="authorized" value="no"> </form>';
        }
        $is_authorized = ($_POST['authorized'] === 'yes');

        $this->_server->handleAuthorizeRequest($request, $response, $is_authorized);
        if ($is_authorized) {
            $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
            //exit("SUCCESS! Authorization Code: $code");
        }
        return $response->send();
    }
}